<template>
  <div class="request-definition-create">
    <header class="mb-8">
      <div class="flex items-center">
        <router-link to="/request/definitions" class="mr-4 text-light-dark hover:text-primary">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
        </router-link>
        <h1 class="glow-text">创建请求定义</h1>
      </div>
      <div class="tech-line mt-2"></div>
    </header>

    <div class="card">
      <form @submit.prevent="saveDefinition">
        <!-- 基本信息 -->
        <div class="mb-8">
          <h2 class="text-xl font-medium mb-6">基本信息</h2>
          
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label class="block text-light-dark mb-2">请求名称 <span class="text-accent-pink">*</span></label>
              <input
                v-model="definitionForm.name"
                type="text"
                class="input w-full"
                placeholder="例如: 获取用户信息"
                required
              />
            </div>
            
            <div>
              <label class="block text-light-dark mb-2">请求方法 <span class="text-accent-pink">*</span></label>
              <select v-model="definitionForm.method" class="input w-full" required>
                <option value="GET">GET</option>
                <option value="POST">POST</option>
                <option value="PUT">PUT</option>
                <option value="DELETE">DELETE</option>
                <option value="PATCH">PATCH</option>
                <option value="HEAD">HEAD</option>
                <option value="OPTIONS">OPTIONS</option>
              </select>
            </div>
            
            <div class="md:col-span-2">
              <label class="block text-light-dark mb-2">请求 URL <span class="text-accent-pink">*</span></label>
              <input
                v-model="definitionForm.url"
                type="text"
                class="input w-full"
                placeholder="例如: https://api.example.com/users/123"
                required
              />
            </div>
            
            <div class="md:col-span-2">
              <label class="block text-light-dark mb-2">描述</label>
              <textarea
                v-model="definitionForm.description"
                class="input w-full h-24"
                placeholder="请输入请求描述..."
              ></textarea>
            </div>
          </div>
        </div>

        <!-- 请求头 -->
        <div class="mb-8">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-medium">请求头</h2>
            <button type="button" @click="addHeader" class="btn btn-outline text-sm">
              <svg class="w-4 h-4 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
              </svg>
              添加请求头
            </button>
          </div>
          
          <div v-if="headers.length === 0" class="text-center py-4 text-light-dark">
            暂无请求头，点击"添加请求头"按钮添加
          </div>
          
          <div v-else>
            <div
              v-for="(header, index) in headers"
              :key="index"
              class="flex items-center mb-4"
            >
              <input
                v-model="header.key"
                type="text"
                class="input w-1/3 mr-2"
                placeholder="Header 名称"
              />
              <input
                v-model="header.value"
                type="text"
                class="input flex-1 mr-2"
                placeholder="Header 值"
              />
              <button
                type="button"
                @click="removeHeader(index)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>

        <!-- 请求体 -->
        <div class="mb-8">
          <h2 class="text-xl font-medium mb-6">请求体</h2>
          
          <div class="mb-4">
            <label class="block text-light-dark mb-2">内容类型</label>
            <select v-model="bodyType" class="input w-full">
              <option value="none">无请求体</option>
              <option value="json">JSON</option>
              <option value="form">Form Data</option>
              <option value="text">Plain Text</option>
            </select>
          </div>
          
          <div v-if="bodyType === 'json'" class="mb-4">
            <textarea
              v-model="definitionForm.body"
              class="input w-full h-64 font-mono"
              placeholder="{\n  \"key\": \"value\"\n}"
            ></textarea>
          </div>
          
          <div v-else-if="bodyType === 'form'">
            <div
              v-for="(param, index) in formParams"
              :key="index"
              class="flex items-center mb-4"
            >
              <input
                v-model="param.key"
                type="text"
                class="input w-1/3 mr-2"
                placeholder="参数名称"
              />
              <input
                v-model="param.value"
                type="text"
                class="input flex-1 mr-2"
                placeholder="参数值"
              />
              <button
                type="button"
                @click="removeFormParam(index)"
                class="text-accent-pink hover:text-accent-pink/80"
                title="删除"
              >
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                </svg>
              </button>
            </div>
            
            <button type="button" @click="addFormParam" class="btn btn-outline text-sm">
              <svg class="w-4 h-4 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
              </svg>
              添加参数
            </button>
          </div>
          
          <div v-else-if="bodyType === 'text'" class="mb-4">
            <textarea
              v-model="definitionForm.body"
              class="input w-full h-64 font-mono"
              placeholder="请输入文本内容..."
            ></textarea>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-between">
          <router-link to="/request/definitions" class="btn btn-outline">取消</router-link>
          <div class="flex space-x-2">
            <button type="button" @click="testRequest" class="btn btn-outline" :disabled="saving || testing">
              <span v-if="testing">测试中...</span>
              <span v-else>
                <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                测试请求
              </span>
            </button>
            <button type="submit" class="btn btn-primary" :disabled="saving || testing">
              <span v-if="saving">保存中...</span>
              <span v-else>
                <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                </svg>
                保存请求定义
              </span>
            </button>
          </div>
        </div>
      </form>
    </div>

    <!-- 测试结果弹窗 -->
    <div v-if="showTestResult" class="fixed inset-0 bg-dark-darker bg-opacity-75 flex items-center justify-center z-50">
      <div class="bg-dark-light rounded-lg w-full max-w-4xl cyber-border">
        <div class="p-6">
          <div class="flex justify-between items-start mb-6">
            <h2 class="text-2xl font-bold">测试结果</h2>
            <button @click="showTestResult = false" class="text-light-dark hover:text-primary">
              <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">状态码</div>
            <div :class="{
              'text-accent-blue': testResponse.status_code < 300,
              'text-accent-yellow': testResponse.status_code >= 300 && testResponse.status_code < 400,
              'text-accent-orange': testResponse.status_code >= 400 && testResponse.status_code < 500,
              'text-accent-pink': testResponse.status_code >= 500
            }">{{ testResponse.status_code }}</div>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">响应时间</div>
            <div>{{ testResponse.response_time.toFixed(2) }} ms</div>
          </div>

          <div class="mb-4">
            <div class="text-light-dark mb-2">响应头</div>
            <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-40 overflow-y-auto">
              <pre>{{ formatHeaders(testResponse.headers) }}</pre>
            </div>
          </div>

          <div class="mb-6">
            <div class="text-light-dark mb-2">响应体</div>
            <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-80 overflow-y-auto">
              <pre>{{ formatBody(testResponse.body) }}</pre>
            </div>
          </div>

          <div class="flex justify-end">
            <button @click="showTestResult = false" class="btn btn-outline">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { requestApi } from '../../api';

// 路由
const router = useRouter();

// 状态变量
const saving = ref(false);
const testing = ref(false);
const showTestResult = ref(false);
const bodyType = ref('none');

// 请求定义表单
const definitionForm = ref({
  name: '',
  method: 'GET',
  url: '',
  description: '',
  headers: {} as Record<string, string>,
  body: ''
});

// 请求头
const headers = ref<{ key: string; value: string }[]>([
  { key: 'Content-Type', value: 'application/json' }
]);

// 表单参数
const formParams = ref<{ key: string; value: string }[]>([]);

// 测试响应
const testResponse = ref({
  status_code: 0,
  response_time: 0,
  headers: {} as Record<string, string>,
  body: ''
});

// 添加请求头
const addHeader = () => {
  headers.value.push({ key: '', value: '' });
};

// 删除请求头
const removeHeader = (index: number) => {
  headers.value.splice(index, 1);
};

// 添加表单参数
const addFormParam = () => {
  formParams.value.push({ key: '', value: '' });
};

// 删除表单参数
const removeFormParam = (index: number) => {
  formParams.value.splice(index, 1);
};

// 格式化请求头
const formatHeaders = (headers: Record<string, string>) => {
  if (!headers) return 'No headers';
  
  return Object.entries(headers)
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n');
};

// 格式化响应体
const formatBody = (body: any) => {
  if (!body) return 'No body';
  
  try {
    // 如果是 JSON 字符串，尝试格式化
    if (typeof body === 'string') {
      const parsed = JSON.parse(body);
      return JSON.stringify(parsed, null, 2);
    }
    // 如果已经是对象，直接格式化
    if (typeof body === 'object') {
      return JSON.stringify(body, null, 2);
    }
  } catch (e) {
    // 如果解析失败，返回原始内容
  }
  
  return body;
};

// 准备请求数据
const prepareRequestData = () => {
  // 处理请求头
  const headersObj: Record<string, string> = {};
  headers.value.forEach(header => {
    if (header.key && header.value) {
      headersObj[header.key] = header.value;
    }
  });
  
  // 处理请求体
  let body = null;
  if (bodyType.value === 'json' || bodyType.value === 'text') {
    body = definitionForm.value.body;
  } else if (bodyType.value === 'form') {
    const formData: Record<string, string> = {};
    formParams.value.forEach(param => {
      if (param.key) {
        formData[param.key] = param.value;
      }
    });
    body = JSON.stringify(formData);
    // 设置 Content-Type 为 form-data
    headersObj['Content-Type'] = 'application/x-www-form-urlencoded';
  }
  
  return {
    name: definitionForm.value.name,
    method: definitionForm.value.method,
    url: definitionForm.value.url,
    description: definitionForm.value.description,
    headers: headersObj,
    body
  };
};

// 测试请求
const testRequest = async () => {
  if (!definitionForm.value.url) {
    alert('请输入请求 URL');
    return;
  }
  
  try {
    testing.value = true;
    const requestData = prepareRequestData();
    
    // 这里应该有一个测试请求的 API，暂时使用模拟数据
    // const response = await requestApi.testDefinition(requestData);
    
    // 模拟响应
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    testResponse.value = {
      status_code: 200,
      response_time: 123.45,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'X-Request-ID': '12345'
      },
      body: JSON.stringify({
        success: true,
        data: {
          id: 123,
          name: 'Test Response',
          timestamp: new Date().toISOString()
        }
      })
    };
    
    showTestResult.value = true;
  } catch (error: any) {
    console.error('测试请求失败:', error);
    alert(`测试请求失败: ${error.response?.data?.error || error.message}`);
  } finally {
    testing.value = false;
  }
};

// 保存请求定义
const saveDefinition = async () => {
  if (!definitionForm.value.name) {
    alert('请输入请求名称');
    return;
  }
  if (!definitionForm.value.url) {
    alert('请输入请求 URL');
    return;
  }
  
  try {
    saving.value = true;
    const requestData = prepareRequestData();
    
    const response = await requestApi.createDefinition(requestData);
    
    if (response && response._id) {
      router.push(`/request/definitions/${response._id}`);
    } else {
      // 模拟成功
      router.push('/request/definitions');
    }
  } catch (error: any) {
    console.error('保存请求定义失败:', error);
    alert(`保存请求定义失败: ${error.response?.data?.error || error.message}`);
  } finally {
    saving.value = false;
  }
};

// 监听 bodyType 变化
watch(bodyType, (newType) => {
  if (newType === 'json') {
    // 设置默认的 JSON 内容类型
    const contentTypeIndex = headers.value.findIndex(h => h.key.toLowerCase() === 'content-type');
    if (contentTypeIndex >= 0) {
      headers.value[contentTypeIndex].value = 'application/json';
    } else {
      headers.value.push({ key: 'Content-Type', value: 'application/json' });
    }
    
    // 如果当前 body 为空，设置默认的 JSON 结构
    if (!definitionForm.value.body) {
      definitionForm.value.body = '{\n  \n}';
    }
  } else if (newType === 'form') {
    // 设置默认的表单内容类型
    const contentTypeIndex = headers.value.findIndex(h => h.key.toLowerCase() === 'content-type');
    if (contentTypeIndex >= 0) {
      headers.value[contentTypeIndex].value = 'application/x-www-form-urlencoded';
    } else {
      headers.value.push({ key: 'Content-Type', value: 'application/x-www-form-urlencoded' });
    }
    
    // 如果当前没有表单参数，添加一个空的
    if (formParams.value.length === 0) {
      formParams.value.push({ key: '', value: '' });
    }
  } else if (newType === 'text') {
    // 设置默认的文本内容类型
    const contentTypeIndex = headers.value.findIndex(h => h.key.toLowerCase() === 'content-type');
    if (contentTypeIndex >= 0) {
      headers.value[contentTypeIndex].value = 'text/plain';
    } else {
      headers.value.push({ key: 'Content-Type', value: 'text/plain' });
    }
  }
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
